<template>
  <a-form
    class="cancel-form"
    :selfUpdate="true"
    @finish="editOk"
    :rules="rules"
    ref="setForm"
    :model="editabDataChead"
    v-if="isBatchHasObj.id && (isMinimumUnit || isBatchHasBloon)"
  >
    <a-row :gutter="[10]">
      <a-col :span="7">
        <a-form-item>
          <span class="text-red-600"> 温馨提示:批量设置会覆盖子题设置 </span>
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="试题类型">
          <span>{{ isBatchHasObj.tmlx }}</span>
        </a-form-item>
      </a-col>
      <a-col :span="5">
        <a-form-item label="试题总分值:" name="tmfz">
          <span>{{ isBatchHasObj.tmfz }}</span>
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item label="试题最小得分单位:">{{ editabDataChead.pydfgc || '--' }}</a-form-item>
      </a-col>
      <a-col :span="24"></a-col>
      <a-col :span="8" v-if="!machineReadableProblem.includes(isBatchHasObj.tmlx)">
        <a-form-item label="评阅模式" name="pyMs">
          <a-select
            :options="pymsOptions"
            v-model:value="editabDataChead.pyMs"
            :autoClearSearchValue="false"
            :disabled="isJdCorrectType(isBatchHasObj)"
            style="width: 100%"
            placeholder="请选择评阅模式"
          />
        </a-form-item>
      </a-col>
      <a-col :span="8" v-if="!machineReadableProblem.includes(isBatchHasObj.tmlx)">
        <a-form-item label="最小得分单位" name="pydfgc">
          <a-input
            placeholder="最小得分单位"
            type="number"
            step="0.5"
            style="width: 100%"
            min="0.5"
            v-model:value="editabDataChead.pydfgc"
          />
        </a-form-item>
      </a-col>
      <a-col :span="8" v-if="!machineReadableProblem.includes(isBatchHasObj.tmlx)">
        <a-form-item label="自评允许最大分差(含)" name="zpFc">
          <a-input
            placeholder="自评允许最大分差(含)，0代表不进行自评校验"
            step="0.5"
            type="number"
            style="width: 100%"
            min="0"
            v-model:value="editabDataChead.zpFc"
          />
        </a-form-item>
      </a-col>
      <a-col
        :span="8"
        v-if="editabDataChead.pyMs == '2' && !machineReadableProblem.includes(isBatchHasObj.tmlx)"
      >
        <a-form-item label="双评分差(含)" name="spFc">
          <a-input
            type="number"
            placeholder="双评分差"
            style="width: 100%"
            step="0.5"
            min="0"
            v-model:value="editabDataChead.spFc"
          />
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item
          label="漏选是否得分"
          name="dxlxScoreType"
          v-if="isBatchHasObj.tmlx == '多项选择题'"
        >
          <a-select
            v-model:value="editabDataChead.dxlxScoreType"
            :options="dxlxOptions"
            style="width: 100%"
            placeholder="请选择"
          />
        </a-form-item>
      </a-col>
      <a-col
        :span="8"
        v-if="isBatchHasObj.tmlx == '多项选择题' && editabDataChead.dxlxScoreType == 'CUSTOM'"
      >
        <a-form-item label="漏选得分" name="dxlxCustomScore">
          <a-input
            placeholder="漏选得分"
            step="0.5"
            style="width: 100%"
            min="0.5"
            v-model:value="editabDataChead.dxlxCustomScore"
          />
        </a-form-item>
      </a-col>
      <a-col :span="24" v-if="!machineReadableProblem.includes(isBatchHasObj.tmlx)">
        <a-form-item label="评阅教师" name="pySzJsfpAccountList">
          <a-select
            v-model:value="editabDataChead.pySzJsfpAccountList"
            mode="multiple"
            :disabled="
              (!!isBatchHasObj.sfzxdtdw && machineReadableProblem.includes(isBatchHasObj.tmlx)) ||
              isJdCorrectType(isBatchHasObj)
            "
            :options="props.fileListProps"
            :filter-option="filterOption"
            show-search
            placeholder="请选择（可按工号搜索）"
          />
        </a-form-item>
      </a-col>
      <a-col :span="isMinimumUnit ? 8 : 24">
        <a-row :gutter="[50, 20]" class="w-full">
          <a-col
            :span="isMinimumUnit ? 24 : 8"
            v-for="(item, index) in editabDataChead.pySzCkdaList"
            :key="index"
          >
            <a-form-item
              :label="item.name + '：试题分值'"
              :class="isMinimumUnit || isBatchHasObj.tmlx == '填空题' ? 'cancel-form-item' : ''"
              :name="['pySzCkdaList', index, 'tmfz']"
              :rules="{ required: true, message: '请设置试题分值', trigger: 'change' }"
              v-if="!isMinimumUnit"
            >
              <a-input
                v-model:value="item.tmfz"
                placeholder="请设置题目分值"
                step="0.5"
                min="0.5"
              ></a-input>
            </a-form-item>
            <a-form-item
              label="参考答案"
              :class="isMinimumUnit || isBatchHasObj.tmlx == '填空题' ? 'cancel-form-item' : ''"
              :name="['pySzCkdaList', index, 'ckda']"
              :rules="{ required: true, message: '答案不能为空', trigger: 'change' }"
            >
              <a-checkbox-group
                v-if="isBatchHasObj.tmlx == '多项选择题'"
                v-model:value="item.ckda"
                width="100%"
              >
                <a-row :gutter="10">
                  <a-col :span="4" v-for="da in item.ckdaOptions" :key="da.value">
                    <a-checkbox :value="da.value" style="line-height: 32px">
                      {{ da.label }}
                    </a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
              <a-radio-group
                v-else-if="machineReadableProblem.includes(isBatchHasObj.tmlx)"
                v-model:value="item.ckda"
              >
                <a-radio :value="da.value" v-for="da in item.ckdaOptions" :key="da.value">{{
                  da.label
                }}</a-radio>
              </a-radio-group>
              <Tinymce
                v-else
                v-model="item.ckda"
                @click="previewImg"
                :height="isBatchHasObj.tmlx == '填空题' ? 100 : 185"
                :showImageUpload="isBatchHasObj.tmlx == '填空题' ? false : true"
                :sjlb="route?.query?.sjlb"
                :kmdm="route?.query?.kmdm"
                :stid="item.stId"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-col>
      <a-col :span="16" v-if="isMinimumUnit || isBatchHasObj.tmlx == '填空题'">
        <a-form-item label="得分点设置" class="!mb-8px"></a-form-item>
        <a-table
          rowKey="stId"
          :dataSource="editabDataChead.pySzDfdList"
          :columns="scoreColumn"
          class="tablstyle"
          bordered
          bodyCell
          :pagination="false"
          size="small"
        >
          <template #headerCell="{ column }">
            <template v-if="column.key === 'handle'">
              <span> 操作 </span>
              <a-button
                type="primary"
                size="small"
                style="margin: 0 0 0 10px"
                :disabled="
                  (isBatchHasObj.childList && isBatchHasObj.childList.length) ||
                  isBatchHasObj.jdFlag == 'y'
                "
                class="!text-12px"
                @click="handelscoreCancel"
              >
                新增得分点
              </a-button>
            </template>
          </template>
          <template #bodyCell="{ column, record, index }">
            <a-form-item
              :name="[`pySzDfdList`, index, column.key]"
              :rules="{
                required: true,
                validator: validatoFun,
                trigger: 'blur',
              }"
              v-if="['contents', 'dfdScore', 'sortNum'].includes(column.dataIndex)"
            >
              <a-input
                :placeholder="column.title"
                :type="column.dataIndex == 'contents' ? 'text' : 'number'"
                :step="column.dataIndex == 'dfdScore' ? 0.5 : 1"
                :min="column.dataIndex == 'dfdScore' ? 0.5 : ''"
                style="width: 100%"
                v-model:value="record[column.key]"
              />
            </a-form-item>
            <a-button
              danger
              type="link"
              v-if="column.key === 'handle'"
              @click="handelstoreDetale(record, index)"
            >
              删除
            </a-button>
          </template>
        </a-table>
      </a-col>
    </a-row>
    <div class="text-center mt-5">
      <a-button class="mr-4" @click="emit('cancelFun')"> 上一步 </a-button>
      <a-button type="primary" html-type="submit"> 保存 </a-button>
    </div>
  </a-form>
  <a-empty :image="simpleImage" v-else :description="'请选择左侧试题后操作'" />
</template>

<script lang="ts" setup>
import { machineReadableProblem, isJdWrongType, isJdCorrectType } from '../index'
import { ref, watch, computed, onMounted, h } from 'vue'
import { Tinymce } from '/@/components/Tinymce'
import { cloneDeep } from 'lodash-es'

import { Empty } from 'ant-design-vue'
const AEmpty = Empty
const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE

import { createImgPreview } from '/@/components/Preview'

import { useMessage } from '/@/hooks/web/useMessage'
const { createMessage, createConfirm } = useMessage()

import { useRoute } from 'vue-router'
const route = useRoute()

// 是否最小试题
const isMinimumUnit = computed(() => {
  // 不存在子试题且是最小得分单位
  return (
    (!props.isBatchHasObj.children || !props.isBatchHasObj.children.length) &&
    props.isBatchHasObj.tmlx !== '填空题' &&
    !machineReadableProblem.includes(props.isBatchHasObj.tmlx) &&
    props.isBatchHasObj.sfzxdtdw === 1
  )
})

// 是否批量设置题型
const isBatchHasBloon = computed(() => {
  return (
    (props.isBatchHasObj.tmlx === '填空题' ||
      machineReadableProblem.includes(props.isBatchHasObj.tmlx)) &&
    ((props.isBatchHasObj?.children &&
      props.isBatchHasObj?.children.length &&
      props.isBatchHasObj?.children[0]?.sfzxdtdw === 1) ||
      ((!props.isBatchHasObj?.children || !props.isBatchHasObj?.children.length) &&
        props.isBatchHasObj?.sfzxdtdw === 1))
  )
})

// 表达校验提交
const setForm = ref()
function editOk() {
  if (
    sysConfig.value.bigScoreCutFlag &&
    sysConfig.value.bigScoreValue < Number(props.isBatchHasObj.tmfz) &&
    editabDataChead.value.pySzDfdList.length == 0 &&
    !isJdCorrectType(props.isBatchHasObj)
  )
    return createMessage.error('得分点设置不能为空')

  if (
    editabDataChead.value.pySzDfdList?.length &&
    !isJdCorrectType(props.isBatchHasObj) 
  ) {
    let numAll = editabDataChead.value.pySzDfdList.reduce(
      (a, b) => a + (Number(b.dfdScore) || 0),
      0
    )
    if (numAll != props.isBatchHasObj.tmfz) return createMessage.error('得分点分值和总分不一致')
  }

  editabDataChead.value.pySzJsfpList = props.fileListProps.filter(item =>
    editabDataChead.value.pySzJsfpAccountList.includes(item.value)
  )
  emit('success', false, editabDataChead.value)
}

// 本地存储
import { useUserStore } from '/@/store/modules/user'
const userStore = useUserStore()
const sysConfig = computed(() => userStore.getSysConfig)

const emit = defineEmits(['update:isBatchHasObj', 'success', 'cancelFun'])
const props = defineProps({
  isBatchHasObj: {
    type: Object,
    default: () => ({}),
  },
  fileListProps: {
    type: Array,
    default: () => [],
  },
} as any)

async function validatoFun(rule, value) {
  if (!value) {
    return Promise.reject('请输入')
  } else if (rule.field.indexOf('dfdScore') > -1) {
    value = Number(value)
    if (value % editabDataChead.value.pydfgc !== 0) {
      return Promise.reject('得分点分值必须为最小得分单位的整数倍')
    } else if (Number(props.isBatchHasObj.tmfz) < value) {
      return Promise.reject('得分点分值不能大于题目分值')
    } else if (sysConfig.value.bigScoreCutFlag && sysConfig.value.bigScoreValue < value) {
      return Promise.reject('得分点分值不能大于大分值分片')
    }
  }
}

const rules = {
  pyMs: [{ required: true, message: '评阅模式不能为空', trigger: 'blur' }],
  pydfgc: [
    {
      required: true,
      validator: async ({}, value) => {
        value = Number(value)
        if (!value) {
          return Promise.reject('最小得分单位不能为空')
        } else if (value % 0.5 !== 0) {
          return Promise.reject('最小得分单位是0.5的倍数')
        } else if (Number(props.isBatchHasObj.tmfz) < value) {
          return Promise.reject('最小得分单位不能大于试题分值')
        } else if (Number(props.isBatchHasObj.tmfz) % value !== 0) {
          return Promise.reject('试题分值必须为最小得分单位的整数倍')
        } else if (sysConfig.value.bigScoreCutFlag && sysConfig.value.bigScoreValue < value) {
          return Promise.reject('最小得分单位不能大于大分值分片')
        }
      },
      trigger: 'blur',
    },
  ],
  dxlxCustomScore: [
    {
      required: true,
      validator: async ({}, value) => {
        value = Number(value)
        if (!value) {
          return Promise.reject('漏选得分不能为空')
        } else if (value % 0.5 !== 0) {
          return Promise.reject('漏选得分是0.5的倍数')
        } else if (
          Number(props.isBatchHasObj.tmfz) / props.isBatchHasObj.children.length <=
          value
        ) {
          return Promise.reject('漏选得分不能大于试题分值')
        }
      },
      trigger: 'blur',
    },
  ],
  dxlxScoreType: [{ required: true, message: '多选题漏选得分类型不能为空', trigger: 'blur' }],
  zpFc: [
    {
      required: true,
      validator: async ({}, value) => {
        value = Number(value)
        if (!value) {
          return Promise.reject('自评允许最大分差(含)需大于零')
        } else if (Number(props.isBatchHasObj.tmfz) < value) {
          return Promise.reject('自评允许最大分差(含)不能大于试题分值')
        }
      },
      trigger: 'blur',
    },
  ],
  spFc: [
    {
      required: true,
      validator: async ({}, value) => {
        value = Number(value)
        if (!value) {
          return Promise.reject('双评分差需大于零')
        } else if (Number(props.isBatchHasObj.tmfz) < value) {
          return Promise.reject('双评分差不能大于试题分值')
        }
      },
      trigger: 'blur',
    },
  ],
  pySzJsfpAccountList: [{ required: true, message: '不能为空', trigger: 'blur' }],
}

const scoreColumn = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    customRender: ({ index }) => {
      return (index += 1)
    },
    width: 60,
    fixed: true,
  },
  {
    title: '得分点',
    dataIndex: 'contents',
    key: 'contents',
  },
  {
    title: '分值',
    key: 'dfdScore',
    dataIndex: 'dfdScore',
    width: 90,
    align: 'center',
  },
  {
    title: '排序',
    key: 'sortNum',
    dataIndex: 'sortNum',
    width: 90,
    align: 'center',
  },
  {
    title: '操作',
    key: 'handle',
    align: 'center',
    width: 160,
    fixed: 'right',
  },
]

// 提交表单
const editabDataChead = ref<any>({
  pyMs: '1',
  pySzCkdaList: [],
  pySzDfdList: [],
})

/**
 * 教师列表
 */
function filterOption(input: string, option: any = {}) {
  return option['label']?.indexOf(input) >= 0
}

/**
 * 评阅模式
 */
const pymsOptions = ref<any[]>([])

/**
 * 漏选得分类型
 */
const dxlxOptions = ref<any[]>([])

// 删除得分点
const handelstoreDetale = async ({}, index) => {
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    content: () => h('span', '您确定删除得分点吗？'),
    onOk: async () => {
      editabDataChead.value.pySzDfdList.splice(index, 1)
    },
  })
}

// 新增得分点
const handelscoreCancel = () => {
  editabDataChead.value.pySzDfdList.push({
    contents: '',
    dfdScore: 0,
    sortNum: editabDataChead.value.pySzDfdList.length + 1,
    stId: props.isBatchHasObj.id,
    id: +new Date(),
  })
}

watch(
  () => props.isBatchHasObj,
  val => {
    handleChangeScore(val)
  },
  { deep: true, immediate: true }
)

function handleChangeScore(val) {
  if (!val.id) return
  if (val.pySzInfoVO?.pyMs) {
    editabDataChead.value = cloneDeep(val.pySzInfoVO)
    editabDataChead.value.pySzJsfpAccountList =
      val.pySzInfoVO?.pySzJsfpList?.map(e => e?.account || e) || []
  }
  editabDataChead.value.tmfz = val.tmfz
  editabDataChead.value.pySzCkdaList = []

  if (val.children && val.children.length) {
    let pySzCkdaInList = cloneDeep(val.pySzInfoVO?.pySzCkdaList)
    let loadList: any[] = []
    for (let i = 0; i < val.children.length; i++) {
      let filterArr: any = {}
      if (val.pySzInfoVO?.pyMs && pySzCkdaInList?.length) {
        for (let j = 0; j < pySzCkdaInList?.length; j++) {
          if (val.children[i].id == pySzCkdaInList[j]?.stId) {
            filterArr = pySzCkdaInList[j] || {}
            if (filterArr.stId && val.tmlx == '多项选择题') {
              filterArr.ckda =
                typeof filterArr.ckda === 'string' ? filterArr.ckda.split(',') : filterArr.ckda
            }
            pySzCkdaInList.splice(j, 1)
            break
          }
        }
      }
      loadList.push({
        stId: val.children[i].id, //试题id
        tmxh: val.children[i].tmxh, //题目序号
        ckda: '', //答案信息
        name: `${val.children[i].tmbh}${+val.children[i].tmbt || ''}`,
        tmfz: val.children[i].tmfz,
        ckdaOptions:
          val.tmlx == '多项选择题' || val.tmlx == '单项选择题'
            ? isJdWrongType.slice(0, val.children[i].xxsl)
            : val.tmlx == '判断题'
            ? isJdWrongType.slice(isJdWrongType.length - 2)
            : [],
        ...filterArr,
      })
    }
    function updateAnimation() {
      if (loadList.length) {
        editabDataChead.value.pySzCkdaList.push(
          ...loadList.splice(0, loadList.length > 10 ? 10 : loadList.length)
        )
        requestAnimationFrame(updateAnimation)
      }
    }
    requestAnimationFrame(updateAnimation)
  } else {
    let pySzCkInfo = {}
    if (val.pySzInfoVO?.pyMs && val.pySzInfoVO?.pySzCkdaList?.length) {
      pySzCkInfo = val.pySzInfoVO.pySzCkdaList[0]
    }
    editabDataChead.value.pySzCkdaList.push({
      stId: val.id, //试题id
      tmxh: val.tmxh, //题目序号
      ckda: '', //答案信息
      ...pySzCkInfo,
      name: `${val.tmbh}${val.tmbt || ''}`,
      tmfz: val.tmfz,
    })
  }
}

function previewImg(event: Element) {
  if (event.target.tagName == 'IMG') {
    createImgPreview({
      imageList: [event.target.src],
    })
  }
}
/**
 * 数据字典
 * @param { String } groupCode 字典组编码
 */
import { getDictionaryList } from '/@/views/teacher/home/index'
onMounted(async () => {
  await getDictionaryList('dxlxScoreType', dxlxOptions)
  await getDictionaryList('pyMs', pymsOptions)
})
</script>

<style lang="less" scoped>
.cancel-form {
  padding-right: 10px;
  height: 100%;
  overflow-y: auto;

  ::v-deep(.ant-table-cell) {
    .ant-form-item {
      margin-bottom: 0;
    }
  }
}

.cancel-form-item {
  flex-direction: column;
  ::v-deep(.ant-form-item-label) {
    text-align: left;
    padding: 0 0 8px;
    line-height: 1.5715;
    white-space: initial;
  }

  ::v-deep(.ant-form-item-control) {
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    min-height: auto;
  }
}
</style>
